<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menu" slot-scope="{ row }">
        <el-button type="text" @click="printQualifiedLabel(row)" icon="el-icon-printer" size="small" v-if="permission.iqc_inspected_print">打印合格标签</el-button>
        <el-button type="text" @click="view(row.id)" icon="el-icon-view" size="small" v-if="permission.iqc_inspected_view">详情</el-button>
      </template>
      <!-- <template slot-scope="{ row }" slot="actualQuantity">
        <span> {{ row.examineResult === 'OK' ? row.sendExamineQuantity : row.disposeQuantity }}</span>
      </template>
      <template slot-scope="{ row }" slot="returnQuantity">
        <span> {{ row.disposeType === 'EXTRACTION' ? row.sendExamineQuantity - row.disposeQuantity : row.disposeType === 'FULLRETURN' ? row.returnQuantity : 0 }}</span>
      </template>
      <template slot-scope="{ row }" slot="disposeQuantity">
        <span>{{ row.examineResult === 'NG' ? row.disposeQuantity : 0 }}</span>
      </template> -->
      <template slot="menuLeft">
        <el-button type="primary" size="small" @click="handleCancel" v-if="permission.iqc_inspected_cancel">撤 销</el-button>
      </template>
    </avue-crud>

    <el-dialog title="查看" append-to-body :visible.sync="showViewDialog" width="60%" :fullscreen="fullscreenViewDialog" @close="cancelView">
      <div slot="title">
        详情<i
          class="el-dialog__close fill-screen-icon"
          :class="fullscreenViewDialog ? 'el-icon-news' : 'el-icon-full-screen'"
          @click="fullscreenViewDialog = !fullscreenViewDialog"
        ></i>
      </div>
      <el-tabs type="card" v-if="showViewDialog" v-model="tabsIndex">
        <el-tab-pane label="IQC检验" name="1">
          <avue-form ref="aplProperties" v-model="inspectionAql" :option="viewOption">
            <template slot="info" v-if="viewModel.attributeResultVOList && viewModel.attributeResultVOList.length > 0">
              <avue-form
                ref="itemProperties"
                v-for="(item, index) in viewModel.attributeResultVOList || []"
                v-model="viewModel.attributeResultVOList[index]"
                :option="itemOption"
                :key="index"
              >
                <template slot="info2">
                  <span style="display: block">检验项： {{ item.item ? item.item.itemName : '' }}</span>
                  <span style="display: block">检验明细项：{{ item.itemAttribute.attributeName }}</span>
                  <span style="display: block">检验标准：{{ item.testCriterion }}</span>
                  <span style="display: block">检验工具：{{ item.itemAttribute.testTool }}</span>
                  <div v-if="isDisplayItemExamineQuantity">
                    <label>抽检数量：</label>
                    <el-input style="width: 200px; margin-bottom: 5px" :value="item.examineQuantity" :disabled="true"> </el-input>
                  </div>
                  <div v-if="item.examineRealValue.type === 'SELECT'">
                    <div style="display: flex; flex-direction: row" v-for="(selectItem, index2) in item.examineRealValue.options" :key="index2">
                      <label>{{ selectItem.label }}：</label>
                      <div style="width: 200px; margin-top: 5px">
                        <el-select disabled v-model="selectItem.selectValue">
                          <el-option v-for="item3 in selectItem.selectList" :key="item3.dictKey" :label="item3.dictValue" :value="item3.dictKey"> </el-option>
                        </el-select>
                      </div>
                    </div>
                  </div>
                  <div v-if="item.examineRealValue.type === 'SINGLE-INPUT'">
                    <div v-for="(scanItem, index2) in item.examineRealValue.options" :key="index2">
                      <label>{{ scanItem.label }}：</label>
                      <el-input style="width: 200px; margin-bottom: 5px" :value="scanItem.value" :disabled="true"> </el-input>
                    </div>
                  </div>
                  <div v-if="item.examineRealValue.type === 'MULTIPLE-INPUT'">
                    <div v-for="(scanItem, index2) in item.examineRealValue.options" :key="index2" style="margin-bottom: 5px">
                      <label>{{ scanItem.label }}：</label>
                      <table border="1">
                        <tr>
                          <th width="50" style="text-align: center">次数</th>
                          <th width="70" style="text-align: center">测试值</th>
                          <th width="120" style="text-align: center">测试结果</th>
                          <th width="70" style="text-align: center">操作</th>
                        </tr>
                        <tr v-for="(result, index3) in item.examineRealValue.options[index2].valueResults" :key="index3">
                          <td style="text-align: center">{{ result.sequence }}</td>
                          <td style="text-align: center">{{ result.value }}</td>
                          <td style="text-align: center">
                            <span>{{ result.result }}</span>
                          </td>
                          <td style="text-align: center; color: red"><div>x</div></td>
                        </tr>
                      </table>
                    </div>
                  </div>
                  <div v-if="item.examineRealValue.type === 'RADIO'">
                    <div v-for="(scanItem, index2) in item.examineRealValue.options" :key="index2">
                      <label>{{ scanItem.label }}：</label>
                      <el-radio v-model="scanItem.valueResults" disabled :label="scanItem.realLabel">{{ scanItem.realLabel }}</el-radio>
                      <el-radio v-model="scanItem.valueResults" disabled :label="scanItem.shamLabel">{{ scanItem.shamLabel }}</el-radio>
                    </div>
                  </div>
                  <div v-if="item.examineRealValue.type === 'SCAN'">
                    <div v-for="(scanItem, index2) in item.examineRealValue.options" :key="index2">
                      <label>{{ scanItem.label + '数量' }}：</label>
                      <el-input style="width: 200px" :value="item.examineRealValue.scanContent.length" :disabled="true"> </el-input>
                    </div>
                  </div>
                </template>
              </avue-form>
            </template>
            <template slot="info" v-else>
              <span></span>
            </template>
            <template slot="attachments">
              <!-------------------->
              <div>
                <div style="display: inline-block; text-align: center" v-for="(item, index) in viewModel.attachments" :key="item.attachmentId">
                  <el-image
                    v-if="item.attachmentType === 'PICTURE'"
                    style="width: 100px; height: 100px; padding-right: 10px; display: block"
                    :src="item.link"
                    @click="openPreview(index, item.link)"
                  ></el-image>
                  <i
                    v-else
                    style="font-size: 70px; color: #909399; width: 100px; height: 100px; padding-right: 10px; display: block"
                    class="el-icon-document"
                    @click="openPreview(index, item.link)"
                  ></i>
                  <el-button type="text" v-if="item.link" icon="el-icon-download" size="small" @click="handleDownload(item)">下载 </el-button>
                </div>
              </div>
            </template>
          </avue-form>
        </el-tab-pane>
        <el-tab-pane label="不良处理" name="2">
          <avue-form ref="aplProperties" v-model="viewModel" :option="failureHandleOption">
            <template slot="inspectionAttachmentList">
              <div>
                <div style="display: inline-block; text-align: center" v-for="(item, index) in viewModel.inspectionAttachmentList" :key="item.attachmentId">
                  <el-image style="width: 100px; height: 100px; padding-right: 10px; display: block" :src="item.link" @click="openPreview(index, item.link)"></el-image>
                  <el-button type="text" v-if="item.link" icon="el-icon-download" size="small" @click="handleDownload(item)">下载 </el-button>
                </div>
              </div>
            </template>
          </avue-form>
        </el-tab-pane>
        <el-tab-pane label="AQL" name="3">
          <div v-for="(item, index) in inspectionAqlList" :key="index">
            <avue-form v-model="inspectionAqlList[index]" :option="aqlOption"> </avue-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <el-dialog append-to-body title="打印合格标签" v-if="printInfoModel" :visible.sync="printInfoModel" @close="printClose" width="35%">
      <avue-form ref="printForm" v-model="printInfo" :option="printInfoOption"> </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="printSubmit"><i class="el-icon-printer"></i><span>打 印</span></el-button>
        <el-button size="small" @click="printClose"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, inspect, cancel, print } from '@/api/quality/iqc-examine';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import { getList as getAttributeConfigList } from '@/api/system/custom-attribute-config';

export default {
  components: {
    userTableConfig,
    CommonModalTemplate
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'IQC_INSPECTED',
      form: {},
      model: {},
      viewModel: {},
      inspectionAqlList: [],
      tabsIndex: '1',
      attachments: [],
      printInfo: {},
      timer: new Date().getTime(),
      printInfoModel: false,
      query: { statusStr: '2,3' },
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      tableOption: {},
      data: [],
      selectData: [],
      code: '00',
      checkIqc: true,
      isDisplayItemExamineQuantity: false,
      option: {
        height: 'calc(100vh - 482px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        addBtn: false,
        delBtn: false,
        editBtn: false,
        selection: true,
        dialogClickModal: false,
        labelWidth: 120,
        menuWidth: 100,
        searchLabelWidth: 90,
        searchMenuSpan: 3,
        searchMenuPosition: 'right',
        menuWidth: 200,
        columnBtn: false,
        column: [
          {
            label: '检验单号',
            prop: 'documentNo',
            search: true,
            // searchOrder: 1,
            searchSpan: 5,
            order: 4,
            rules: [
              {
                required: true,
                message: '请输入检验单号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验方式',
            prop: 'examineMode',
            order: 8,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=inspection_mode',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请输入检验方式',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '物料编码',
            prop: 'partNo',
            searchOrder: 1,
            search: true,
            searchSpan: 5,
            order: 1,
            rules: [
              {
                required: true,
                message: '请输入物料编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '物料名称',
            prop: 'partName',
            search: true,
            searchOrder: 2,
            searchSpan: 5,
            order: 2,
            rules: [
              {
                required: true,
                message: '请输入物料名称',
                trigger: 'blur'
              }
            ]
          },
          // {
          //   label: '物料批次',
          //   prop: 'lotNo',
          //   order: 4,
          //   rules: [
          //     {
          //       required: true,
          //       message: '请输入物料批次',
          //       trigger: 'blur'
          //     }
          //   ]
          // },
          {
            label: '物料规格',
            prop: 'partModel',
            order: 4,
            rules: [
              {
                required: true,
                message: '请输入物料规格',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '送检数量',
            prop: 'sendExamineQuantity',
            rules: [
              {
                required: true,
                message: '请输入送检数量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验数量',
            prop: 'examineQuantity',
            rules: [
              {
                required: true,
                message: '请输入检验数量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验结果',
            prop: 'examineResult',
            type: 'select',
            searchSpan: 5,
            search: true,
            order: 5,
            dicData: [
              {
                label: '合格',
                value: 'OK'
              },
              {
                label: '不合格',
                value: 'NG'
              }
            ],
            rules: [
              {
                required: true,
                message: '请输入检验结果',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '不良处理方式',
            prop: 'disposeType',
            order: 7,
            dicData: [
              {
                label: '正常',
                value: 'NORMAL'
              },
              {
                label: '批量退货',
                value: 'FULLRETURN'
              },
              {
                label: '让步收料',
                value: 'DEVIATION'
              },
              {
                label: '部分特采',
                value: 'EXTRACTION'
              }
            ],
            rules: [
              {
                required: true,
                message: '请输入检验结果',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '退货数量',
            prop: 'returnQuantity'
          },
          {
            label: '特采数量',
            prop: 'extractionQuantity',
            order: 7,
            rules: [
              {
                required: true,
                message: '请输入检验结果',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '实收数量',
            prop: 'realityQuantity'
          },
          {
            label: '采购单',
            prop: 'sheetNo',
            search: true,
            searchSpan: 5,
            order: 6
          },
          {
            label: '供应商编码',
            prop: 'partnerCode',
            search: true,
            searchSpan: 5,
            order: 3
          },
          {
            label: '供应商名称',
            prop: 'partnerName',
            // search: true,
            searchSpan: 5
          },
          {
            label: '送验日期',
            prop: 'sendExamineDate',
            searchOrder: 20,
            searchSpan: 6,
            type: 'date',
            searchType: 'daterange',
            order: 18,
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
          },
          {
            label: '检验日期',
            prop: 'examineDate',
            search: true,
            searchOrder: 20,
            searchSpan: 6,
            type: 'date',
            searchType: 'daterange',
            order: 18,
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
          }
        ]
      },

      showDialog: false, //IQC检验结果模态框
      fullscreenHandlingDialog: false,
      showViewDialog: false,
      fullscreenViewDialog: false,
      propertiesOption: {
        emptyBtn: false,
        submitBtn: false,
        column: [
          {
            label: '处理类型',
            prop: 'disposeType',
            labelWidth: '100',
            span: 20,
            require: true,
            type: 'radio',
            dicData: [
              {
                label: '正常',
                value: 'NORMAL'
              },
              {
                label: '批量退货',
                value: 'FULLRETURN'
              },
              {
                label: '让步收料',
                value: 'DEVIATION'
              },
              {
                label: '部分特采',
                value: 'EXTRACTION'
              }
            ],
            rules: [
              {
                required: true,
                message: '请选择处理类型',
                trigger: 'blur'
              }
            ],
            control: (val, form) => {
              let that = this;
              if (val == 'FULLRETURN') {
                that.model.returnOrSpecialQuantity = that.model.sendExamineQuantity;
                this.model.extractionQuantity = '';
                return {
                  returnOrSpecialQuantity: { display: true, label: '退货数量' },
                  extractionQuantity: { display: false }
                };
              } else if (val == 'DEVIATION') {
                that.model.returnOrSpecialQuantity = that.model.sendExamineQuantity;
                this.model.extractionQuantity = '';
                return {
                  returnOrSpecialQuantity: { display: true, label: '特采数量' },
                  extractionQuantity: { display: false }
                };
              } else if (val == 'EXTRACTION') {
                return {
                  returnOrSpecialQuantity: { display: false },
                  extractionQuantity: { display: true }
                };
              }
            }
          },
          {
            label: '检验单号',
            prop: 'documentNo',
            span: 6,
            disabled: true
          },
          {
            label: '物料编码',
            prop: 'partNo',
            span: 6,
            disabled: true
          },
          {
            label: '收货数量',
            prop: 'sendExamineQuantity',
            span: 6,
            disabled: true
          },
          {
            label: '退货数量',
            prop: 'returnOrSpecialQuantity',
            span: 6,
            disabled: true
          },
          {
            label: '特采数量',
            formslot: true,
            prop: 'extractionQuantity',
            span: 6,
            rules: [
              {
                required: true,
                message: '请输入特采数量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '',
            labelWidth: '40',
            prop: 'attachmentLabel',
            require: true,
            formslot: true
          },
          {
            label: '',
            prop: 'iqcNGAttachments',
            type: 'upload',
            span: 20,
            loadText: '图片上传中，请稍等',
            propsHttp: {
              url: 'link',
              name: 'attachId',
              res: 'data'
            },
            listType: 'picture',
            limit: 3,
            accept: 'image/png, image/jpeg, image/jpg',
            tip: '只能上传png/jpeg/jpg文件',
            action: '/api/blade-resource/oss/endpoint/put-file-attach',
            rules: [
              {
                required: true,
                message: '请上传IQC检验报告',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '备注/原因',
            prop: 'disposeRemark',
            span: 20,
            type: 'textarea',
            maxRows: 3,
            minRows: 3,
            rules: [
              {
                message: '请填写备注/原因',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      printInfoOption: {
        labelWidth: 150,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '物料名称',
            prop: 'partName',
            disabled: true,
            span: 20,
            row: true
          },
          {
            label: '物料规格',
            prop: 'partModel',
            disabled: true,
            span: 20,
            row: true
          },
          {
            label: '供应商',
            prop: 'partnerName',
            span: 20,
            row: true,
            disabled: true
          },
          {
            label: '批次',
            prop: 'vendorLotNo',
            span: 20,
            row: true,
            disabled: true
          },
          {
            label: '进料日期',
            prop: 'vendorDate',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            type: 'date',
            span: 20,
            row: true,
            rules: [
              {
                required: true,
                message: '请选择进料日期',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '有效期',
            prop: 'validityTime',
            type: 'number',
            controls: false,
            minRow: 1,
            span: 20,
            row: true,
            rules: [
              {
                required: true,
                message: '请输入有效期',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验人员',
            prop: 'examineByName',
            span: 20,
            disabled: true,
            row: true
          },
          {
            label: '打印机',
            prop: 'equipmentName',
            span: 20,
            type: 'search',
            placeholder: '请选择 打印机',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择打印机',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openPrintersModal();
            }
          },
          {
            label: '标签模版',
            prop: 'labelTemplateName',
            span: 20,
            type: 'search',
            placeholder: '请选择 标签模板',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择标签模板',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openLabelTemplateModal();
            }
          }
        ]
      },
      aqlOption: {
        emptyBtn: false,
        submitBtn: false,
        column: [
          {
            label: '抽样标准',
            prop: 'samplingStandard',
            type: 'select',
            span: 8,
            labelWidth: 160,
            row: true,
            disabled: true,
            dicUrl: '/api/blade-system/dict/dictionary?code=sample_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            control: (val, form) => {
              if (val === 'MIL-STD-1916 C-0') {
                return {
                  severityCode: {
                    display: false
                  },
                  levelType: {
                    display: false
                  },
                  levelCode: {
                    display: false
                  }
                };
              } else {
                return {
                  severityCode: {
                    display: true
                  },
                  levelType: {
                    display: true
                  },
                  levelCode: {
                    display: true
                  }
                };
              }
            }
          },
          {
            label: '严重程度',
            prop: 'severityCode',
            span: 8,
            labelWidth: 160,
            type: 'select',
            row: true,
            disabled: true,
            dicUrl: '/api/blade-system/dict/dictionary?code=sample_plan',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '检验水平',
            prop: 'levelType',
            span: 8,
            row: true,
            labelWidth: 160,
            disabled: true,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=aql_inspection_level',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '检验水平代码',
            prop: 'levelCode',
            span: 8,
            row: true,
            labelWidth: 160,
            disabled: true
          },
          {
            label: '质量水平代码',
            prop: 'limitCode',
            labelWidth: 160,
            span: 8,
            disabled: true
          },
          {
            label: '抽检数量',
            prop: 'sampleQuantity',
            span: 6,
            labelWidth: 80,
            disabled: true
          },
          {
            label: 'Ac',
            prop: 'acceptQuantity',
            span: 4,
            labelWidth: 40,
            disabled: true
          },
          {
            label: 'Re',
            prop: 'rejectQuantity',
            span: 4,
            labelWidth: 40,
            disabled: true
          },
          {
            label: '严重缺陷抽样水平代码',
            prop: 'severityLimitCode',
            labelWidth: 160,
            span: 8,
            disabled: true
          },
          {
            label: '抽检数量',
            prop: 'severitySampleQuantity',
            span: 6,
            labelWidth: 80,
            disabled: true
          },
          {
            label: 'Ac',
            prop: 'severityAcceptQuantity',
            span: 4,
            labelWidth: 40,
            disabled: true
          },
          {
            label: 'Re',
            prop: 'severityRejectQuantity',
            span: 4,
            labelWidth: 40,
            disabled: true
          },
          {
            label: '主要缺陷抽样水平代码',
            prop: 'majorLimitCode',
            labelWidth: 160,
            span: 8,
            disabled: true
          },
          {
            label: '抽检数量',
            prop: 'majorSampleQuantity',
            span: 6,
            labelWidth: 80,
            disabled: true
          },
          {
            label: 'Ac',
            prop: 'minorAcceptQuantity',
            span: 4,
            labelWidth: 40,
            disabled: true
          },
          {
            label: 'Re',
            prop: 'majorRejectQuantity',
            span: 4,
            labelWidth: 40,
            disabled: true
          },
          {
            label: '次要缺陷抽样水平代码',
            prop: 'minorLimitCode',
            labelWidth: 160,
            span: 8,
            disabled: true
          },
          {
            label: '抽检数量',
            prop: 'minorSampleQuantity',
            span: 6,
            labelWidth: 80,
            disabled: true
          },
          {
            label: 'Ac',
            prop: 'minorAcceptQuantity',
            span: 4,
            labelWidth: 40,
            disabled: true
          },
          {
            label: 'Re',
            prop: 'minorRejectQuantity',
            span: 4,
            labelWidth: 40,
            disabled: true
          }
        ]
      },
      viewOption: {
        emptyBtn: false,
        submitBtn: false,
        labelWidth: '160',
        column: [
          {
            label: '抽样标准',
            prop: 'samplingStandard',
            type: 'select',
            span: 8,
            disabled: true,
            dicUrl: '/api/blade-system/dict/dictionary?code=sample_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            control: (val, form) => {
              if (val === 'MIL-STD-1916 C-0') {
                return {
                  severityCode: {
                    display: false
                  },
                  levelType: {
                    display: false
                  },
                  levelCode: {
                    display: false
                  }
                };
              } else {
                return {
                  severityCode: {
                    display: true
                  },
                  levelType: {
                    display: true
                  },
                  levelCode: {
                    display: true
                  }
                };
              }
            }
          },
          {
            label: '严重',
            prop: 'severityCode',
            span: 8,
            disabled: true,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=sample_plan',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
            // control: (val, form) => {
            //   switch (val) {
            //     case 'NORMAL':
            //       this.inspectionAql.severityCode = '正常';
            //       break;
            //     case 'REDUCE':
            //       this.inspectionAql.severityCode = '加宽';
            //       break;
            //     case 'TIGHTEH':
            //       this.inspectionAql.severityCode = '加严';
            //       break;
            //     default:
            //       break;
            //   }
            // }
          },
          {
            label: '检验水平',
            prop: 'levelType',
            span: 8,
            disabled: true,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=aql_inspection_level',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '检验水平代码',
            prop: 'levelCode',
            span: 8,
            disabled: true
          },
          {
            label: '质量水平代码',
            prop: 'limitCode',
            span: 8,
            disabled: true
          },
          {
            label: '检验数量',
            prop: 'examineQuantity',
            span: 8,
            disabled: true
          },
          {
            label: '抽检数量',
            prop: 'sampleQuantity',
            span: 8,
            disabled: true
          },
          {
            label: 'Ac',
            prop: 'acceptQuantity',
            span: 8,
            disabled: true
          },
          {
            label: 'Re',
            prop: 'rejectQuantity',
            span: 8,
            disabled: true
          },
          {
            labelWidth: 60,
            label: '',
            prop: 'info',
            span: 24,
            hide: true,
            row: true,
            formslot: true
          },
          {
            label: '综合判定结果',
            prop: 'examineResult',
            type: 'radio',
            span: 24,
            disabled: true,
            labelWidth: 100,
            row: true,
            dicData: [
              {
                label: 'OK',
                value: 'OK'
              },
              {
                label: 'NG',
                value: 'NG'
              }
            ]
          },
          {
            label: '附件',
            prop: 'attachments',
            //  listType:'picture',
            //  type: 'upload',
            span: 24,
            formslot: true,
            disabled: true
          },
          {
            label: '备注/原因',
            prop: 'remark',
            span: 20,
            type: 'textarea',
            maxRows: 3,
            minRows: 3,
            disabled: true,
            row: true
          }
        ]
      },
      itemOption: {
        emptyBtn: false,
        submitBtn: false,
        labelWidth: '160',
        column: [
          {
            labelWidth: 60,
            label: '',
            prop: 'info2',
            span: 24,
            hide: true
          },
          {
            label: '检验结果',
            prop: 'examineResult',
            type: 'radio',
            span: 24,
            disabled: true,
            labelWidth: 100,
            row: true,
            formslot: true,
            dicData: [
              {
                label: 'OK',
                value: 'OK'
              },
              {
                label: 'NG',
                value: 'NG'
              }
            ]
          },
          {
            label: 'CRI（严重问题）数',
            prop: 'criQuantity',
            span: 8,
            disabled: true
          },
          {
            label: 'MAJ（主要问题）数',
            prop: 'majQuantity',
            span: 8,
            disabled: true
          },
          {
            label: 'MIN（次要问题）数',
            prop: 'minQuantity',
            span: 8,
            disabled: true
          }
        ]
      },
      failureHandleOption: {
        emptyBtn: false,
        submitBtn: false,
        labelWidth: '160',
        column: [
          {
            label: '处理人员',
            prop: 'disposeUser',
            span: 8,
            disabled: true
          },
          {
            label: '处理时间',
            prop: 'disposeDate',
            span: 8,
            disabled: true
          },
          {
            label: '处理类型',
            prop: 'disposeType',
            span: 8,
            disabled: true,
            control: (val, form) => {
              switch (val) {
                case 'NORMAL':
                  this.viewModel.disposeType = '正常';
                  break;
                case 'EXTRACTION':
                  this.viewModel.disposeType = '特采';
                  break;
                case 'DEVIATION':
                  this.viewModel.disposeType = '让步收';
                  break;
                case 'FULLRETURN':
                  this.viewModel.disposeType = '全退';
                  break;
                default:
                  break;
              }
            }
          },
          {
            label: '送检数量',
            prop: 'sendExamineQuantity',
            span: 8,
            disabled: true
          },
          {
            label: '退货数量',
            prop: 'returnQuantity',
            span: 8,
            disabled: true
          },
          {
            label: '特采数量',
            prop: 'extractionQuantity',
            span: 8,
            disabled: true
          },
          {
            label: '实际数量',
            prop: 'realityQuantity',
            span: 8,
            disabled: true
          },
          {
            label: '备注/原因',
            prop: 'disposeRemark',
            span: 20,
            type: 'textarea',
            maxRows: 3,
            minRows: 3,
            disabled: true
          },
          {
            label: '附件',
            prop: 'inspectionAttachmentList',
            listType: 'picture',
            type: 'upload',
            span: 24,
            formslot: true,
            disabled: true
          }
        ]
      },
      customAttributeList: [] //扩展属性
      // viewOption2: {
      //   emptyBtn: false,
      //   submitBtn: false,
      //   labelWidth: '160',
      //   column: [
      //     {
      //       label: 'IQC检验结果',
      //       labelslot: true,
      //       prop: 'examineResult',
      //       span: 8,
      //       type: 'input',
      //       disabled: true,
      //       row: true
      //     },
      //     {
      //       label: 'IQC检验报告',
      //       span: 16,
      //       prop: 'attachments',
      //       require: true,
      //       formslot: true
      //     },
      //     {
      //       label: '备注/原因',
      //       prop: 'remark',
      //       span: 20,
      //       type: 'textarea',
      //       maxRows: 3,
      //       minRows: 3,
      //       disabled: true,
      //       row: true
      //     }
      //   ]
      // }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {};
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  created() {
    let path = this.$route.path;
    getAttributeConfigList(path).then((res) => {
      this.customAttributeList = this._get(res, 'data.data', []);
      this._forEach(this.customAttributeList, (item, index) => {
        this.option.column.splice(1 + index, 0, {
          label: item.lableCnName,
          prop: item.attributeKey,
          type: item.controlType,
          value: item.defaultValue,
          dispaly: item.enabled,
          search: true
        });
      });
      this.$refs.crud.refreshTable();
    });
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    /**
     * 提交检验结果
     */
    async submit() {
      // this.model.extFields = null;
      let attribute = this.model;
      let done;
      let validDate = await new Promise((resolve, reject) => {
        this.$refs.badhandlingProperties.validate((valid, done) => {
          done = done;
          if (valid) {
            resolve();
            done();
          } else {
          }
        });
      });
      Promise.all([validDate]).then(() => {
        if (attribute.disposeType === 'EXTRACTION' && parseInt(attribute.extractionQuantity) > parseInt(attribute.sendExamineQuantity)) {
          this.$message({
            type: 'warning',
            message: '特采数量不可超过收货数量!'
          });
          return;
        }

        attribute.statusStr = '2,3';
        attribute.disposeType != 'EXTRACTION' ? (attribute.disposeQuantity = attribute.sendExamineQuantity) : (attribute.disposeQuantity = attribute.extractionQuantity);
        let attachments = attribute.iqcNGAttachments.map((attachment) => {
          return {
            link: attachment.value,
            attachmentId: attachment.label,
            attachmentType: 'NG'
          };
        });
        //合并待检上传的图片
        attribute.attachments = attribute.attachments.concat(attachments);
        console.log(attribute.disposeType, attribute, 5555555);
        inspect(attribute).then(
          () => {
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.$refs.badhandlingProperties.resetForm();
            this.showDialog = false;
          },
          (error) => {
            window.console.log(error);
          }
        );
        done();
      });
    },

    //只能输入正整数
    changeValue(value) {
      if (this.model.extractionQuantity.length == 1) {
        value = value.replace(/[^1-9.]/g, '');
      } else {
        value.replace(/\D/g, '');
      }
      this.model.extractionQuantity = value;
      return value;
    },
    //限制不能输入小数点
    keypressOverlimitRate(e) {
      let code = e.keyCode;
      if (code === 46) {
        e.preventDefault();
      }
    },

    cancel() {
      this.showDialog = false;
      this.model = {};
    },
    cancelView() {
      this.showViewDialog = false;
      this.viewModel = {};
      this.attachments = [];
    },

    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = { statusStr: '2,3' };
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.examineDate && params.examineDate.length > 0) {
        params.startExamineDate = params.examineDate[0];
        params.endExamineDate = params.examineDate[1];
        // let startExamineDate = new Date(params.examineDate[0]);
        // startExamineDate.setHours(0, 0, 0);
        // let endExamineDate = new Date(params.examineDate[1]);
        // endExamineDate.setHours(23, 59, 59);
        // params.startExamineDate = this.$moment(startExamineDate).format('YYYY-MM-DD  HH:mm:ss');
        // params.endExamineDate = this.$moment(endExamineDate).format('YYYY-MM-DD  HH:mm:ss');
      }
      delete params.examineDate;
      params.statusStr = '2,3';
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    onLoad(page, params = {}) {
      this.loading = true;
      params.documentType = 'IQC';
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this._forEach(data.records, (item) => {
          if (!item.returnQuantity) {
            item.returnQuantity = 0;
          }
          if (!item.extractionQuantity) {
            item.extractionQuantity = 0;
          }
          if (!item.realityQuantity) {
            item.realityQuantity = 0;
          }
        });
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    //不良处理
    async badHandling(id) {
      this.model = {};
      this.showDialog = true;
      this.fullscreenHandlingDialog = false;
      getDetail(id).then((res) => {
        if (!res.data.data.examineResult) {
          res.data.data.examineResult = 'OK';
        }
        this.model = res.data.data;
        this.model.disposeType = 'FULLRETURN';
        this.model.returnOrSpecialQuantity = this.model.sendExamineQuantity;
      });
    },
    //打印合格标签
    printQualifiedLabel(row) {
      this.printInfo.partName = row.partName;
      this.printInfo.partModel = row.partModel;
      this.printInfo.examineByName = row.examineByName;
      this.printInfo.vendorLotNo = row.vendorLotNo;
      this.printInfo.partnerName = row.partnerName;
      this.printInfoModel = true;
    },
    printClose() {
      this.printInfo = {};
      this.$refs.printForm.resetFields();
      this.printInfoModel = false;
    },
    printSubmit() {
      this.$refs.printForm.validate((valid, done) => {
        if (valid) {
          let params = {
            printId: this.printInfo.equipmentId,
            labelTemplateId: this.printInfo.labelTemplateId,
            printPlaceholder: {
              partname: this.printInfo.partName,
              partmodel: this.printInfo.partModel,
              vendorlotno: this.printInfo.vendorLotNo,
              vendordate: this.printInfo.vendorDate,
              examByName: this.printInfo.examineByName,
              validityTime: this.printInfo.validityTime
            }
          };
          let reg = /^\+?[1-9]\d*$/;
          if (!reg.test(this.printInfo.validityTime)) {
            this.$message({
              type: 'warning',
              message: '有效期为正整数!'
            });
            return;
          }
          // if (!this.printInfo.equipmentName) {
          //   this.$message({
          //     type: 'warning',
          //     message: '请选择打印机!'
          //   });
          //   return;
          // }
          // if (!this.printInfo.labelTemplateName) {
          //   this.$message({
          //     type: 'warning',
          //     message: '请选择标签模板!'
          //   });
          //   return;
          // }
          print(params).then(
            (res) => {
              this.printInfo = {};
              this.$refs.printForm.resetFields();
              this.printInfoModel = false;
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              done();
            },
            (error) => {
              done();
            }
          );
        }
      });
    },
    getSelectedRows(rowData, title) {
      switch (this.modalName) {
        case 'labelTemplateModal':
          this.$set(this.printInfo, 'labelTemplateId', rowData.id);
          this.$set(this.printInfo, 'labelTemplateName', rowData.fileName);
          break;
        case 'printersModal':
          this.$set(this.printInfo, 'equipmentId', rowData.id);
          this.$set(this.printInfo, 'equipmentName', rowData.name);
          break;
        default:
          break;
      }
    },
    async view(id) {
      this.viewModel = {};
      this.showViewDialog = true;
      this.fullscreenViewDialog = false;
      getDetail(id).then((res) => {
        let data = res.data.data;
        this.inspectionAql = data.inspectionAqlList[0];
        this.inspectionAql.disposeRemark = data.disposeRemark;
        this.inspectionAql.examineResult = data.examineResult;
        this.inspectionAql.examineQuantity = data.examineQuantity;
        this.viewModel = {
          ...data
        };
        if (!this.viewModel.returnQuantity) {
          this.viewModel.returnQuantity = 0;
        }
        if (!this.viewModel.extractionQuantity) {
          this.viewModel.extractionQuantity = 0;
        }

        if (!this.viewModel.realityQuantity) {
          this.viewModel.realityQuantity = 0;
        }
        // this.viewModel.actualQuantity = this.viewModel.examineResult === 'OK' ? this.viewModel.sendExamineQuantity : this.viewModel.disposeQuantity;
        // this.viewModel.rejectQuantity =
        //   this.viewModel.disposeType === 'EXTRACTION'
        //     ? this.viewModel.sendExamineQuantity - this.viewModel.disposeQuantity
        //     : this.viewModel.disposeType === 'FULLRETURN'
        //     ? this.viewModel.rejectQuantity
        //     : 0;
        this._forEach(this.viewModel.attributeResultVOList || [], (item) => {
          item.examineRealValue = JSON.parse(item.examineRealValue);
        });
        //   this.viewModel.attachments = this._map(this.viewModel.attachments, (item) => {
        //     return item.link;
        //   })

        this.inspectionAqlList = data.inspectionAqlList || [];
        this.isDisplayItemExamineQuantity = this.inspectionAqlList.some((item) => item.levelType === 'SPECIAL');
        console.log(this.inspectionAqlList, 99988);
      });
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    closeDialog() {
      this.$refs.badhandlingProperties.resetForm();
    },
    handleDownload(item) {
      window.open(`${item.link}`);
    },

    openPreview(index = 0, link) {
      this.$ImagePreview([{ url: link }], index, {
        closeOnClickModal: false
      });
    },
    handleCancel() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择一条数据');
        return;
      }
      if (this.selectionList.length > 1) {
        this.$message.warning('只能选择一条数据');
        return;
      }
      this.$confirm('撤销后，检验记录及报表将同步撤销！', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return cancel({
            ids: this.ids,
            documentType: 'IQC'
          });
        })
        .then(() => {
          // 刷新表格数据并重载
          this.data = [];
          this.$refs.crud.refreshTable();
          this.$refs.crud.toggleSelection();
          // 表格数据重载
          this.onLoad(this.page);

          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    /**
     * 获取打印机
     */
    openPrintersModal() {
      this.modalName = 'printersModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择打印机（双击进行选择）',
        url: '/api/mes-product/ems-equipment/page?type=PRINTER',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '打印机编码',
            prop: 'code',
            search: true,
            searchLabelWidth: 110
          },
          {
            label: '打印机名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 110
          }
        ]
      };
    },
    /**
     * 打开标签模板模态框
     */
    openLabelTemplateModal() {
      this.modalName = 'labelTemplateModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择标签模版（双击进行选择）',
        url: '/api/mes-admin/labeltemplate/page?status=1',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '标签名称',
            prop: 'fileName',
            search: true
          },
          {
            label: '标签代码',
            prop: 'code',
            search: true
          },
          {
            label: '版本名称',
            prop: 'revision'
          },
          {
            label: '缩略图',
            prop: 'thumbnailUrl'
          },
          {
            label: '打印标签',
            prop: 'fileUrl'
          }
        ]
      };
    }
  }
};
</script>

<style scoped lang="scss">
$size: 16px;
.view-style {
  font-weight: bold;
  font-size: $size;
}
.iqc-placeholder {
  font-size: $size;
  color: #aaaaaa;
}

.iqcDialog {
  ::v-deep input[type='file'] {
    display: none !important;
  }
}
$BORDER-STYLE: 1px solid #f0f0f0 !important;
::v-deep .inspection-btn:hover {
  background-color: #dedede;
}
::v-deep .el-dialog__header {
  border-bottom: $BORDER-STYLE;
}

::v-deep .el-dialog__footer {
  border-top: $BORDER-STYLE;
}

.fill-screen-icon {
  color: #909399;
  font-size: 15px;
  float: right;
  padding-right: 25px;
  &:hover {
    color: #409eff;
  }
}

.group-title {
  border-bottom: 1px solid rgb(240, 240, 240) !important;
  font-size: 16px;
  font-weight: 500;
  height: 50px;
  line-height: 50px;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 20px;
}
</style>
